﻿#include <libemb/Socket.h>
#include <libemb/Tracer.h>
#include <libemb/FileUtil.h>
#include <libemb/StrUtil.h>
#include <libemb/ArgUtil.h>

using namespace libemb;

class MyUdpServer : public UdpServer{
public:
    bool onNewDatagram(UdpSocket& udpSocket,char* buf, int len)
    {
    	udpSocket.sendData((const char *) buf, len, 1000);
		return true;
    }   
};

int main(int argc, char* argv[])
{
	std::string argValue;
	ArgOption  argOption;
	uint16 port=5555;
	std::string ip = "0.0.0.0";
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	Tracer::getInstance().addSink(std::make_shared<STDSink>()).start();
	argOption.addOption("h", 0);	/* -h:帮助 */
	argOption.addOption("p", 1);	/* -p:指定端口 */
	argOption.addOption("i", 1);	/* -i:指定IP */
	argOption.parseArgs(argc,argv);	/* 解析参数 */

	if(argOption.getValue("h", argValue))
	{
		FilePath filePath(argv[0]);
		TRACE_YELLOW("udp server help:");
		TRACE_YELLOW("%s [-h] [-p port] [-i ip]",CSTR(filePath.baseName()));
		TRACE_YELLOW("        -h  help");
		TRACE_YELLOW("        -p  server port");
		TRACE_YELLOW("        -i  server ip");
		return RC_OK;
	}

	if(argOption.getValue("p", argValue))
	{
		port = (uint16)StrUtil::stringToInt(argValue);
	}
	else
	{
		TRACE_ERR("udp server need a port: [-p port]!");
		return RC_ERROR;
	}
	
	if(argOption.getValue("i", argValue))
	{
		ip = argValue;
	}

	Thread serThread;
    MyUdpServer server;
    if (!server.setup(ip,port))
    {
    	TRACE_ERR("udp server init error: %s:%d",CSTR(ip),port);
		return RC_ERROR;
	}
    if (!serThread.start(server))
    {
    	TRACE_ERR("udp server start error.");
		return RC_ERROR;
	}
	Thread::msleep(2000);
	TRACE_INFO("udp server start ok: %s:%d",CSTR(ip),port);
	while(1)
	{
		Thread::msleep(2000);
	}
    return 0;
}
